const app = getApp()

Page({
  page: {
    size: 5,
    num: 1,
  },

  data: {
    tabs: [
      { key: -1, text: '全部' },
      { key: 2, text: '待收货', info: '' },
      { key: 1, text: '已完成', info: '' },
    ],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    backRefresh: false,
    status: -1,
    pageLoading: false
  },

  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : -1;
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    this.setData({ pullDownRefreshing: true });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({ pullDownRefreshing: false });
        callback && callback();
      })
      .catch((err) => {
        this.setData({ pullDownRefreshing: false });
        Promise.reject(err);
      });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },

  getOrderList(state = -1,msg) {
    this.setData({
      pageLoading: true
    })
    if(state != -1){
      try{
        wx.cloud.database().collection('book-order').where({
          state: state
        }).orderBy('_updateTime','desc').get({
          success:res=>{
            this.setData({
              orderList: res.data
            })
            if(msg){
              wx.showToast({
                title: msg,
                duration: 800
              })
            }
          }
        })
      } finally {
        this.setData({
          pageLoading: false
        })
      }
    }else{
      try{
        wx.cloud.database().collection('book-order').orderBy('state','desc').orderBy('_updateTime','desc').get({
          success:res=>{
            this.setData({
              orderList: res.data
            })
            if(msg){
              wx.showToast({
                title: msg,
                duration: 800
              })
            }
          }
        })
      } finally {
        this.setData({
          pageLoading: false
        })
      }
    }
  },

  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  onTabChange(e) {
    const { value } = e.detail;
    this.setData({
      status: value,
    });
    this.refreshList(value);
  },
  refreshList(status = -1) {
    // this.page = {
    //   size: this.page.size,
    //   num: 1,
    // };
    this.setData({ curTab: status, orderList: [] });

    return Promise.all([
      this.getOrderList(status),
    ]);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    const { order } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/order-detail/index?orderNum=${order.orderNum}`,
    });
  },
  confirmOrder(e){
    wx.showModal({
      title: '确认收货',
      content: '请确认是否已经收到货？',
      success:(res) =>{
        if (res.confirm) {
          wx.cloud.database().collection('book-order').where({
            userid: app.globalData.userInfo._id,
            orderNum: e.currentTarget.dataset.order.orderNum
          }).update({
            data:{
              state: 1,
              _updateTime: Date.now()
            },
            success:result=>{
              this.getOrderList(1,'收货成功')
              this.setData({
                status: 1,
              });
            }
          })
        }
      },
    });
  },
  deleteOrder(e){
    wx.showModal({
      content: '是否删除该订单？',
      success:(res) =>{
        if (res.confirm) {
          wx.cloud.database().collection('book-order').where({
            userid: app.globalData.userInfo._id,
            orderNum: e.currentTarget.dataset.order.orderNum
          }).remove({
            success:result=>{
              this.getOrderList(this.data.curTab,'删除成功')
            }
          })
        }
      },
    });
  }
});
